package com.xiaomei.manager.web.aliyun.OSS;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;

	public class AliyunUpload {		
	    private static Logger logger = Logger.getLogger(AliyunUpload.class);
	    private static OSSClient ossClient = null;
	    private static final Date expiration = new Date(new Date().getTime() + 3600 * 1000 * 24);  
		static {
			// endpoint以杭州为例，其它region请按实际情况填写
			String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
			// accessKey请登录https://ak-console.aliyun.com/#/查看
			String accessKeyId = "rUNUcDWgnxUDs3gr";
			String accessKeySecret = "OyC9b9o7zKdp6ulS9XIhe2r1nLe79z";

			// 创建OSSClient实例
			ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		}
	    
		public static OSSClient getInstance() {
			return ossClient;
		}
		
	    //创建一个Bucket  
	    public static void ensureBucket(String bucketName)throws OSSException, ClientException{  
	        try {  
	            // 创建bucket, 判断bucket是否存在  
	            boolean exists = ossClient.doesBucketExist(bucketName);  
	            if(!exists){  
	                ossClient.createBucket(bucketName);  
	            }else{  
	                  
	            }  
	        } catch (ServiceException e) {  
	            System.out.println(e.getErrorCode() + "  " + e.getErrorMessage());  
	                throw e;  
	        }  
	    }  
	          
	    // 获取指定bucket下的所有Object信息  
	    public void getObjects(OSSClient client,String bucketName){  
	        ObjectListing listing = client.listObjects(bucketName);  
	        // 遍历所有Object  
	        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {  
	            System.out.println(objectSummary.getKey());  
	        }        
	    }  
	      
	    // 删除一个Bucket和其中的Objects   
	    public static void deleteBucket(OSSClient client, String bucketName)  
	            throws OSSException, ClientException {  
	  
	        ObjectListing ObjectListing = client.listObjects(bucketName);  
	        List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();  
	        for (int i = 0; i < listDeletes.size(); i++) {  
	            String objectName = listDeletes.get(i).getKey();  
	            // 如果不为空，先删除bucket下的文件  
	            client.deleteObject(bucketName, objectName);  
	        }  
	        client.deleteBucket(bucketName);  
	    }  
	  
	    // 把Bucket设置为所有人可读  
	    public static void setBucketPublicReadable(OSSClient client, String bucketName)  
	            throws OSSException, ClientException {  
	        //创建bucket  
	        client.createBucket(bucketName);  
	  
	        //设置bucket的访问权限，public-read-write权限  
	        client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);  
	    } 
		
		/**
		 * 删除OSS对象
		 * @param bucketName
		 * @param key
		 * @return
		 */
		public static boolean removeOSSObject(String bucketName, String key) {
			try {
				// 删除Object
				ossClient.deleteObject(bucketName, key);
				
				//关闭client
                //ossClient.shutdown();
				
				return true;
			} catch(Exception e) {;
				logger.error("删除OSS对象失败", e);
				return false;
			}
		}
		
		/**
		 * 删除OSS对象
		 * @param bucketName
		 * @param key
		 * @return
		 */
		public static boolean removeOssObject(String value) {
			try {
				String bucketName = "xm-chuxing-common";
				String key = value.substring(value.lastIndexOf("com/") + 4, value.length());
				
				// 删除Object
				ossClient.deleteObject(bucketName, key);
				
				//关闭client
                //ossClient.shutdown();
				
				return true;
			} catch(Exception e) {;
				logger.error("删除OSS对象失败", e);
				return false;
			}
		}
		
		
		
	    // 上传文件 MultipartFile multipartFile  
	    public static boolean uploadMultipartFile(String key, String bucketName, MultipartFile multipartFile) throws OSSException, ClientException, FileNotFoundException {  
	  
	         try {  
	            // 获取指定文件的输入流  
	             InputStream content = multipartFile.getInputStream();  
	             // 创建上传Object的Metadata  
	             ObjectMetadata meta = new ObjectMetadata();  
	             // 必须设置ContentLength  
	             meta.setContentLength(multipartFile.getSize());  
	             meta.setContentType("image/*");  
	             ossClient.putObject(bucketName, key, content, meta); 
	             return true;
	        } catch (IOException e) {  
	            // TODO Auto-generated catch block  
	            e.printStackTrace();
	            return false;
	        }  
	    }

		// 上传文件 MultipartFile multipartFile
		public static boolean uploadObject(String key, String bucketName, InputStream inputStream, Integer size) throws OSSException, ClientException {

			// 创建上传Object的Metadata
			ObjectMetadata meta = new ObjectMetadata();
			// 必须设置ContentLength
			meta.setContentLength(size);
			meta.setContentType("image/*");
			ossClient.putObject(bucketName, key, inputStream, meta);
			return true;
		}

		//上传文件 file
	    public static void uploadFile(String key, File file, String bucketName) throws OSSException, ClientException, FileNotFoundException {  
	    // 获取指定文件的输入流  
	    InputStream content = new FileInputStream(file);  
	    // 创建上传Object的Metadata  
         ObjectMetadata meta = new ObjectMetadata();  
	     // 必须设置ContentLength  
	     meta.setContentLength(file.length());  
	         meta.setContentType("image/*");  
	     ossClient.putObject(bucketName, key, content, meta);  	     
	    }    
	    
	    /**
		 * 获取oss访问地址
		 */
//		public static String getOSSUrl(String fileName) {
//			return "http://xm-chuxing-common.oss-cn-hangzhou.aliyuncs.com/" + fileName;
//		}
		
		/**
		 * 获取oss访问地址
		 */
		public static String getOSSUrl(String bucketName, String fileName) {
			return "http://"+ bucketName +".oss-cn-hangzhou.aliyuncs.com/" + fileName;
		}
	    
	  //生成URL  
	    public static URL getUrl(String key, String bucketName){  
	        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);  
	        return url;  
	    }  
	    
	  // 下载文件  
	    public static void downloadFile(OSSClient client, String bucketName, String key, String fileDownloadPath)  
	            throws OSSException, ClientException {  
	        client.getObject(new GetObjectRequest(bucketName, key), new File(fileDownloadPath));  
	    }  
	      
	  //创建Bucket 里的虚拟文件夹  
	    public static void createFileDir(String dir, String bucketName)throws OSSException, ClientException{  
	        ensureBucket(bucketName);  
	        try {  
	            ossClient.getObject("", dir);  
	        } catch (ServiceException e) {  
	            // TODO Auto-generated catch block  
	            if(e.getErrorCode().equals("NoSuchKey")){  
	                //要创建的文件夹名称,在满足Object命名规则的情况下以"/"结尾  
	                  String objectName = dir + "/";  
	                  ObjectMetadata objectMeta = new ObjectMetadata();  
	                    
	                  /*这里的size为0,注意OSS本身没有文件夹的概念,这里创建的文件夹本质上是一个size为0的Object,dataStream仍然可以有数据   */  
	                  byte[] buffer = new byte[0];  
	                  ByteArrayInputStream in = new ByteArrayInputStream(buffer);  
	                  objectMeta.setContentLength(0);  
	                  try {  
	                      //创建文件上传目录  
	                      ossClient.putObject("", objectName, in, objectMeta);  
	                  }catch(ServiceException se){  
	                      System.out.println(se.getErrorCode() + "  " + se.getErrorMessage());  
	                      throw e;  
	                  }  
	                  finally {  
	                      try {  
	                          in.close();  
	                      } catch (IOException ioe) {  
	                          // TODO Auto-generated catch block  
	                          ioe.printStackTrace();  
	                      }  
	                  }  
	            }  
	              
	        }  
	             
	      }  
	}

